//-------------------------------------------------------------------------
// Copyright (c) 2000-2010 Ufinity. All Rights Reserved.
//
// This software is the confidential and proprietary information of
// Ufinity
//
// Original author: Administrator
//
//-------------------------------------------------------------------------
// UFINITY MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
// THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE, OR NON-INFRINGEMENT. UFINITY SHALL NOT BE
// LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
// MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
//
// THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
// CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
// PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
// NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
// SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
// SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
// PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). UFINITY
// SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
// HIGH RISK ACTIVITIES.
//-------------------------------------------------------------------------
package com.password.safe.component;

import java.awt.Color;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import com.password.safe.constants.Constants;
import com.password.safe.controller.UpdatePasswordController;
import com.password.safe.dto.Messages;
import com.password.safe.util.UpdatePasswordObserver;
import com.password.safe.util.UserCache;


public class UpdatePasswordFrame extends JFrame implements UpdatePasswordObserver {
	private static final long serialVersionUID = -4083063796679750224L;
	private static Logger logger = Logger.getLogger(UpdatePasswordFrame.class);
	
	private JLabel usernameLabel;
	private JTextField username;
	private JLabel oldPasswordLabel;
	private JPasswordField oldPassword;
	private JLabel newPasswordLabel;
	private JPasswordField newPassword;
	private JLabel repasswordLabel;
	private JPasswordField repassword;
	
	private UpdatePasswordController updatePasswordController;
	
	public UpdatePasswordFrame() {
		this.setTitle("Update Password");
		this.getContentPane().setLayout(null);
        // 下面两行是取得屏幕的高度和宽度
        double lx = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
        double ly = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
        this.setLocation(new Point((int) (lx / 2) - 150, (int) (ly / 2) - 200));// 设定窗口出现位置
        this.setSize(340, 240);// 设定窗口大小
        
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        usernameLabel = new JLabel(Constants.LABEL_USERNAME);
        usernameLabel.setBounds(30, 10, 120, 25);
        
        username = new JTextField();
        username.setEditable(false);
        username.setBounds(150, 10, 120, 20);
        username.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        username.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {
            }

            public void keyReleased(KeyEvent e) {
            	// auto submit
            	if (Constants.KEY_CODE_ENTER == e.getKeyCode()) {
            		updatePassword();
            	}
            }

            public void keyTyped(KeyEvent e) {
                if (getUsername().getText().length() > Constants.USERNAME_MAX_LENGTH) {
                	getUsername().setText(getUsername().getText().substring(0, Constants.USERNAME_MAX_LENGTH));
                }
            }
        });
        
        oldPasswordLabel = new JLabel(Constants.LABEL_OLD_PASSWORD);
        oldPasswordLabel.setBounds(30, 40, 120, 25);
        oldPassword = new JPasswordField();
        oldPassword.setBounds(150, 40, 120, 20);
        oldPassword.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        oldPassword.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {
            }

            public void keyReleased(KeyEvent e) {
            	// auto submit
            	if (Constants.KEY_CODE_ENTER == e.getKeyCode()) {
            		updatePassword();
            	}
            }

            public void keyTyped(KeyEvent e) {
                if (getOldPassword().getText().length() > 6) {
                	getOldPassword().setText(getOldPassword().getText().substring(0, 6));
                }
            }
        });
        
        newPasswordLabel = new JLabel(Constants.LABEL_NEW_PASSWORD);
        newPasswordLabel.setBounds(30, 70, 120, 25);
        newPassword = new JPasswordField();
        newPassword.setBounds(150, 70, 120, 20);
        newPassword.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        newPassword.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {
            }

            public void keyReleased(KeyEvent e) {
            	// auto submit
            	if (Constants.KEY_CODE_ENTER == e.getKeyCode()) {
            		updatePassword();
            	}
            }

            public void keyTyped(KeyEvent e) {
                if (getNewPassword().getText().length() > Constants.PASSWORD_MAX_LENGTH) {
                	getNewPassword().setText(getNewPassword().getText().substring(0, Constants.PASSWORD_MAX_LENGTH));
                }
            }
        });
        
        repasswordLabel = new JLabel(Constants.LABEL_RE_PASSWORD);
        repasswordLabel.setBounds(30, 100, 120, 25);
        repassword = new JPasswordField();
        repassword.setBounds(150, 100, 120, 20);
        repassword.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        repassword.addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {
            }

            public void keyReleased(KeyEvent e) {
            	if (Constants.KEY_CODE_ENTER == e.getKeyCode()) {
            		updatePassword();
            	}
            }

            public void keyTyped(KeyEvent e) {
                if (getRepassword().getText().length() > Constants.PASSWORD_MAX_LENGTH) {
                	getRepassword().setText(getRepassword().getText().substring(0, Constants.PASSWORD_MAX_LENGTH));
                }
            }
        });
        
     // 确定按钮
        JButton ok = new JButton(Constants.BUTTON_CONFIRM);
        ok.setBounds(50, 130, 60, 25);
        ok.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }

            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
            	updatePassword();
            }
        });

        // 取消按钮
        JButton cancel = new JButton(Constants.BUTTON_CANCEL);
        cancel.setBounds(120, 130, 60, 25);
        cancel.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
            	resetFrame();
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }

            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
            }
        });
        
        this.getContentPane().add(usernameLabel);
        this.getContentPane().add(username);
        this.getContentPane().add(oldPasswordLabel);
        this.getContentPane().add(oldPassword);
        this.getContentPane().add(newPasswordLabel);
        this.getContentPane().add(newPassword);
        this.getContentPane().add(repasswordLabel);
        this.getContentPane().add(repassword);
        this.getContentPane().add(ok);
        this.getContentPane().add(cancel);
	}

	public JTextField getUsername() {
		return username;
	}

	public JTextField getOldPassword() {
		return oldPassword;
	}

	public JTextField getNewPassword() {
		return newPassword;
	}

	public JTextField getRepassword() {
		return repassword;
	}
	
	public UpdatePasswordController getUpdatePasswordController() {
		return updatePasswordController;
	}

	public void setUpdatePasswordController(
			UpdatePasswordController updatePasswordController) {
		this.updatePasswordController = updatePasswordController;
		this.updatePasswordController.addObserver(this);
	}

	public void updatePassword() {
		logger.debug("update password submit...");
		String rightPassword = UserCache.getPassword();
		String oldPsd = String.valueOf(this.oldPassword.getPassword());
		if (rightPassword.equals(oldPsd)) {
			logger.debug("the old password is right");
			String newPsd = String.valueOf(this.newPassword.getPassword());
			String rePsd = String.valueOf(this.repassword.getPassword());
			Messages messages = Messages.getInstance();
			if (newPsd == null || rePsd == null || newPsd.trim().equals("")) {
				logger.debug("new password is blank...");
				messages.addMessage(Constants.ERROR_MSG_PASSWORD_IS_BLANK, "the password is blank.");
				updatePasswordController.notifyFailed(messages);
			} else if (!newPsd.trim().equals(rePsd.trim())) {
				logger.debug("two new passwords is not equal...");
				messages.addMessage(Constants.ERROR_MSG_PASSWORD_NOT_EQUAL, "the password is not match.");
				updatePasswordController.notifyFailed(messages);
			} else {
				logger.debug("user's input is correct...");
				updatePasswordController.updatePassword(newPsd);
			}
		} else {
			logger.debug("the old password is wrong");
			Messages messages = Messages.getInstance();
			messages.addMessage(Constants.ERROR_MSG_PASSWORD_ERROR, "the old password you input is wrong.");
			updatePasswordController.notifyFailed(messages);
		}
	}

	public void updatePasswordSuccess(Messages messages) {
		this.setVisible(false);
	}
	
	public void prepareUpdate() {
		logger.debug("update password frame show...");
		this.username.setText(UserCache.getUsername());
		this.setVisible(true);
		resetFrame();
	}

	public void updatePasswordFailed(Messages messages) {
		this.setVisible(true);
		resetFrame();
		if (messages.getMessage(Constants.ERROR_MSG_PASSWORD_IS_BLANK) != null) {
			this.newPasswordLabel.setText(Constants.ERROR_MSG_BLANK_NEW_PASSWORD);
			this.newPasswordLabel.setForeground(Color.RED);
			getNewPassword().setBorder(BorderFactory.createLineBorder(Color.RED));
		} else if (messages.getMessage(Constants.ERROR_MSG_PASSWORD_NOT_EQUAL) != null) {
			this.newPasswordLabel.setText(Constants.ERROR_MSG_PASSWORD_NOT_EQUAL);
			this.newPasswordLabel.setForeground(Color.RED);
			this.repasswordLabel.setText(Constants.ERROR_MSG_PASSWORD_NOT_EQUAL);
			this.repasswordLabel.setForeground(Color.RED);
			getNewPassword().setBorder(BorderFactory.createLineBorder(Color.RED));
			getRepassword().setBorder(BorderFactory.createLineBorder(Color.RED));
		} else if (messages.getMessage(Constants.ERROR_MSG_PASSWORD_ERROR) != null) {
			this.oldPasswordLabel.setText(Constants.ERROR_MSG_OLD_PASSWORD);
			this.oldPasswordLabel.setForeground(Color.RED);
			getOldPassword().setBorder(BorderFactory.createLineBorder(Color.RED));
		}
	}
	
	void resetFrame() {
		String blank = "";
		this.oldPasswordLabel.setText(Constants.LABEL_OLD_PASSWORD);
		this.oldPasswordLabel.setForeground(this.usernameLabel.getForeground());
		this.oldPassword.setBorder(this.username.getBorder());
		this.newPasswordLabel.setText(Constants.LABEL_NEW_PASSWORD);
		this.newPasswordLabel.setForeground(this.usernameLabel.getForeground());
		this.newPassword.setBorder(this.username.getBorder());
		this.repasswordLabel.setText(Constants.LABEL_RE_PASSWORD);
		this.repasswordLabel.setForeground(this.usernameLabel.getForeground());
		this.repassword.setBorder(this.username.getBorder());
        getOldPassword().setText(blank);
        getNewPassword().setText(blank);
        getRepassword().setText(blank);
	}
}
